<?php

class AlibabaAction extends AliCommonAction {
	
	public $cmTableName 	= 'Alibaba';
	
	
	//初始化方法，所有方法必须传 :sessionKey  引入SDK入口文件
	public function _initialize(){
		
		parent::_initialize();
	}
	
	//获取关键词分组
	public function getTagList(){
		
		
		$sessionKey = $this->sessionKey;
		
		
   
		$c = new TopClient; 
		$c->appkey 		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		
		$req  = new AlibabaScbpTagListRequest; 
		$resp = $c->execute($req, $sessionKey);
		
		$return  = array();
		$return['status'] =  1;
		$return['data']   =  $resp;
		
		$this->returnData($return);
	}
	
	//获取关键词列表
	public function getAdKeyWordList(){
		
		$sessionKey 	=  $this->sessionKey;
		$tag_name   	=  empty($_REQUEST['tag_name'])?'':$_REQUEST['tag_name'];
		$per_page_size  =  empty($_REQUEST['per_page_size'])?'20':$_REQUEST['per_page_size'];
		$to_page  		=  empty($_REQUEST['to_page'])?'1':$_REQUEST['to_page'];
		$keyword  		=  empty($_REQUEST['keyword'])?'':$_REQUEST['keyword'];
		$status  		=  empty($_REQUEST['status'])?'':$_REQUEST['status'];
		$qs_star  		=  empty($_REQUEST['qs_star'])?'':$_REQUEST['qs_star'];
		$is_exact  		=  empty($_REQUEST['is_exact'])?'':$_REQUEST['is_exact'];
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		$req = new AlibabaScbpAdKeywordGetRequest;
		$query_dto = new KeywordQuery;
		
		if(!empty($tag_name)){ 
			$query_dto->tag_name		=	$tag_name; 
		}
		
		if(!empty($to_page)){ 
			$query_dto->to_page		=	$to_page; 
		}
		if(!empty($keyword)){ 
			$query_dto->keyword		=	$keyword;
		}
		if(!empty($status)){ 
			$query_dto->status		=	$status;
		}
		if(!empty($qs_star)){ 
			$query_dto->qs_star		=	$qs_star;
		}
		if(!empty($is_exact) && $is_exact=='Y' ){ 
			$query_dto->is_exact	=    "Y";
		}
		$query_dto->per_page_size	=	$per_page_size;
		
		
		$req->setQueryDto(json_encode($query_dto));
		$resp = $c->execute($req, $sessionKey);
		
		$return  = array();
		$return['status'] 	=  1;
		$return['data']   	=  $resp;
		$return['tag_name'] =  $tag_name;
		
		$this->returnData($return);
	}
	
	//批量搜索关键词
	public function getAdKeyWordBatch(){
		
		
		$sessionKey 	=  $this->sessionKey;
		$keywordStr 	=  empty($_REQUEST['keywordStr'])?'':$_REQUEST['keywordStr'];
		$is_exact 		=  empty($_REQUEST['is_exact'])?'Y':$_REQUEST['is_exact'];
		
		$keywordArr = explode(DOT,trim($keywordStr,DOT));
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		$req = new AlibabaScbpAdKeywordGetRequest;
		$query_dto = new KeywordQuery;
		$query_dto->is_exact="Y";
		
		$allResult = array();
		
		foreach($keywordArr as $keyword){
			
			$query_dto->keyword=$keyword;
			$req->setQueryDto(json_encode($query_dto));
			$resp = $c->execute($req, $sessionKey);
			
			$allResult[] = $resp;
		}
		
		$return  = array();
		$return['status'] =  1;
		$return['data']   =  $allResult;
		
		$this->returnData($return);
		
	}
	
	//获取关键词前5价格
	public function getTopFivePrice(){
		
		$sessionKey =  $this->sessionKey;
		$keywordStr    =  empty($_REQUEST['keywordStr'])?'':$_REQUEST['keywordStr'];
		
		$keywordArr = explode(DOT,trim($keywordStr,DOT));
		
		$c = new TopClient;
		$c->appkey		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		
		$allData = array();
		foreach($keywordArr as $val){
			
			$req = new AlibabaScbpAdKeywordRankPriceGetRequest;
			$req->setKeyword($val);  
			$resp = $c->execute($req, $sessionKey); 
			
			$dataRow = array();
			$dataRow['keyword'] = $val;
			$dataRow['result']  = $resp;
			
			$allData[] = $dataRow;
		}
		
		
		
		$return  = array();
		$return['status'] =  1;
		$return['data']   =  $allData;
		$this->returnData($return);
	}
	
	
	//关键词改价
	public function adKeywordPriceUpdate(){
		
		$sessionKey =  $this->sessionKey;
		$keyword 	=  empty($_REQUEST['keyword'])?'':$_REQUEST['keyword'];
		$toPrice 	=  empty($_REQUEST['toPrice'])?'0':$_REQUEST['toPrice'];
		
		if(empty($toPrice)){
			
			$return['status'] =  -1;
			$return['msh']    =  'toPrice:不能为空';
			$this->returnData($return);
		}
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		
		$req = new AlibabaScbpAdKeywordPriceUpdateRequest;
		$req->setAdKeyword( $keyword );
		$req->setPriceStr($toPrice);
		$resp = $c->execute($req, $sessionKey);
		
		$return  = array();
		$return['status'] =  1;
		$return['data']   =  $resp;
		$this->returnData($return);
	}
	
	//获取关键词预估排名
	public function getAdKeywordRank(){
		
		$sessionKey =  $this->sessionKey;
		$keyword 	=  empty($_REQUEST['keyword'])?'':$_REQUEST['keyword'];
		$index 		=  empty($_REQUEST['index'])?'-1':$_REQUEST['index'];
		
		if(empty($keyword)){
			
			$return['status'] =  -1;
			$return['msh']    =  'keyword:不能为空';
			$this->returnData($return);
		}
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey   = APP_SECRET;
		$req 			= new AlibabaScbpAdKeywordRankGetRequest;
		
		$req->setKeyword($keyword);
		$resp = $c->execute($req, $sessionKey);
		
		$return  = array();
		$return['status'] =  1;
		$return['index']  =  $index;
		$return['data']   =  $resp;
		$this->returnData($return);
	}
	
	//批量获取关键词预估排名
	public function getAdKeywordRankBatch(){
		
		$sessionKey =  $this->sessionKey;
		$keywordStr =  empty($_REQUEST['keywordStr'])?'':$_REQUEST['keywordStr'];
		$index 		=  empty($_REQUEST['index'])?'':$_REQUEST['index'];
		
		$return  = array();
		$return['status'] =  1;
		
		if(empty($keywordStr)){ 
			
			$return['status'] =  0;
			
			$this->returnData($return);
		}
		
		$keywordArr = explode(DOT,$keywordStr);
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey   = APP_SECRET;
		$req 			= new AlibabaScbpAdKeywordRankGetRequest;
		
		$resArr = array();
		//echo DOT;exit;
		//AAA($keywordArr);
		foreach($keywordArr as $key=>$val){
			
			if(!empty($val)){
				
				$req->setKeyword($val);
				$resp = $c->execute($req, $sessionKey);
				
				$data = array();
				$data['key'] 	=  $val;
				$data['result'] =  $resp;
				
				$resArr[] = $data;
			}
		}
		
		
		$return['data']   =  $resArr;
		$return['index']  =  $index;
		
		$this->returnData($return);
	}
	
	//批量开启，暂停关键词
	public function asyBatchStartOrStopKeywords(){
		
		$sessionKey 	=  $this->sessionKey;
		$keywordStr 	=  empty($_REQUEST['keywordStr'])?'':$_REQUEST['keywordStr'];
		$action 		=  empty($_REQUEST['action'])?'':$_REQUEST['action'];
		
		$return  = array();
		$return['status'] =  1;
		$return['data']   =  1;
		if(empty($keywordStr)){ 
			
			$return['status'] =  0;
			
			$this->returnData($return);
		}
		
		$keywordArr = explode(DOT,trim($keywordStr,DOT));
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey   = APP_SECRET;
		$req 			= new AlibabaScbpAdKeywordStatusBatchupdateRequest;
		
		//$words = array();
		foreach($keywordArr as $key=>$val){
			
			
			$keyword_update_dto_list = new KeywordUpdateDto;
			
			$keyword_update_dto_list->keyword_id = $val;
			$keyword_update_dto_list->value      = $action=='stopped'?'stopped':'in_promotion';
			
			$req->setKeywordUpdateDtoList(json_encode($keyword_update_dto_list));
			$resp = $c->execute($req, $sessionKey);
			
			$dataRow = array();
			$dataRow['status'] = $action;
			
			$where = array();
			$where['keyword_id'] =  $val;
			$where['member_id']  =  $this->member_id;
			M('bidgroup_words')->where($where)->save($dataRow);
		}
		
		//$str = json_encode($words);
		
		
		// $req->setKeywordUpdateDtoList($str);
		// $resp = $c->execute($req, $sessionKey);
		
		$this->returnData($return);
	}
	
	
	public function muplitUpdatePrice(){
		
		
		$sessionKey =  $this->sessionKey;
	
		$c = new TopClient;
		$c->appkey = APP_KEY;
		$c->secretKey = APP_SECRET;
		$req = new AlibabaScbpAdKeywordPriceBatchupdateRequest;
		
		$keyword_update_dto_list = new KeywordUpdateDto;
		$str = 						  '[{"keyword_id":"77624451993","value":"4.6"},{"keyword_id":"77625994739","value":"3.2"}]';
		$req->setKeywordUpdateDtoList($str);
		
		$resp = $c->execute($req, $sessionKey);
		
		AAA($resp);
	}
	
	//获取当前生效时段 -> 根据时段获取
	public function getNeedUpdatePriceWords(){
		
		$member_id 	    = $this->member_id;
		
		$is_auto 		= empty($_REQUEST['type'])?'':$_REQUEST['type'];
		
		$memberInfo     = M('member')->where('member_id='.$member_id)->find();
		
		if( $memberInfo['is_trusteeship']==1 ){
			
			//file_get_contents('http://localhost:30005?member_id='.$member_id);
			$member_id 	    = $this->member_id;
			$precord_id =  empty($_REQUEST['precord_id'])?'':$_REQUEST['precord_id'];
			
			import('ORG.Util.Page');
			
			$where = array();
			$where['member_id'] = $member_id;
			if(!empty($precord_id)){
				$where['precord_id'] = array('gt',$precord_id);
			}
			
			$count      = M('precord')->where($where)->count();
			$Page       = new Page($count,5);
			$show       = $Page->show();
			$lists = M('precord')->where($where)->order('precord_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
			
			$lists = empty($lists)?array():$lists;
			
			$return  = array();
			$return['status']      = 1;
			$return['data']   	   =  $lists;
			$return['member_id']   =  $member_id;
			$this->returnData($return);
			exit;
		}
		
		if($is_auto=='auto'){
			
		}else{
			
			$is_trusteeship = $this->is_trusteeship;
			
			if($is_trusteeship=='1'){
				
				$member_id 	    = $this->member_id;
				$precord_id =  empty($_REQUEST['precord_id'])?'':$_REQUEST['precord_id'];
				
				import('ORG.Util.Page');
				
				$where = array();
				$where['member_id'] = $member_id;
				if(!empty($precord_id)){
					$where['precord_id'] = array('gt',$precord_id);
				}
				
				$count      = M('precord')->where($where)->count();
				$Page       = new Page($count,5);
				$show       = $Page->show();
				$lists = M('precord')->where($where)->order('precord_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
				
				$lists = empty($lists)?array():$lists;
				
				$return  = array();
				$return['status']      = 1;
				$return['data']   	   =  $lists;
				$return['member_id']   =  $member_id;
				$this->returnData($return);
			}
		}
		
		$sessionKey 	=  $this->sessionKey;
		$username 		= empty($_REQUEST['username'])?'':$_REQUEST['username'];
		
		
		
		$nowHour   = date('G');
		$nowMinute = date('i');
		$nowSecond = date('s');
		$nowTimeStamp = $nowHour.$nowMinute.$nowSecond;
		
		//获取启动的竞价组  1 为启动
		$where = array();
		$where['bid_status']= 1;
		$where['member_id'] = $member_id;
		$groupList = M('bidgroup')->where($where)->select();
		
		foreach($groupList as $keyGropp=>$group){
			
			$where = array();
			$where['group_id']   = $group['bidgroup_id'];
			$where['status']     = 1;
			
			//获取该组已经启动的时间方案
			$strategyList = array();
			$strategyList = M('strategy')->where($where)->select();
			
			foreach($strategyList as $keyStra=>$strategy){
				
				$timeStartArr   = explode(DOT,$strategy['startTime']);
				$timeStartStamp = $timeStartArr[0].getFullTime($timeStartArr[1]).getFullTime($timeStartArr[2]);
				
				$timeEndArr   = explode(DOT,$strategy['endTime']);
				$timeEndStamp = $timeEndArr[0].getFullTime($timeEndArr[1]).getFullTime($timeEndArr[2]);
				
				if( $nowTimeStamp<=$timeEndStamp && $nowTimeStamp>=$timeStartStamp ){
					
					if( empty($groupList[$keyGropp]['strategy']) ){
						
						$groupList[$keyGropp]['strategy'] = $strategy;
					}else{
						if($strategy['is_default']==0){
							$groupList[$keyGropp]['strategy'] = $strategy;
						}
						
					}
					
				}
				
			}
			
		}
		
		//获取竞价组下所有的关键词
		$allWords 	 = array();
		$where 		 = '1 ';
		
		if(!empty($groupList)){
			
			$tempStr = ' AND ( ';
			
			foreach($groupList as $key=>$group){
				
				if($key==0){
					$tempStr.=' bidgroup_id='.$group['bidgroup_id'].' ';
				}
				if($key>0){
					$tempStr.=' OR bidgroup_id='.$group['bidgroup_id'].' ';
				}
				if($key==count($groupList)-1){
					$tempStr.=' ) ';
				}
				
			}
			$where.=$tempStr;
			$where.=' AND qs_star>=3 AND status="in_promotion" ';
		}else{
			
			$where = '0';
		}
		
		$limit = ' limit 0,5 ';
		$order = ' ORDER BY last_price_time ASC ';
		$SQL = 'select * from bidgroup_words where '.$where.$order.$limit; 
		$allWords = M()->query($SQL);
		
		//AAA($SQL);
		//循环插入词的组信息，出价格策略信息
		foreach($allWords as $wordKey=>$word){
			
			
			
			foreach($groupList as $group2Key=>$group2){
				
				
				if($group2['bidgroup_id']==$word['bidgroup_id']){
					
					$allWords[$wordKey]['groupInfo'] = $group2;
				}
			}
			
			
		}
		
		
		
		//循环获取词的前5价格，基础价格
		foreach($allWords as $wordKey2=>$word2){
			
			$c = new TopClient;
			$c->appkey		= APP_KEY;
			$c->secretKey 	= APP_SECRET;
			
			$req = new AlibabaScbpAdKeywordRankPriceGetRequest;
			$req->setKeyword($word2['keyword']);  
			$resp = $c->execute($req, $sessionKey);
			
			$topFiveResult = json_decode(json_encode($resp),true);
			$topFiveResult = $topFiveResult['rank_price_list']['string'];
			
			for($i=0;$i<=4;$i++){
				
				if(empty($topFiveResult[$i])){
					$topFiveResult[$i] = 0.0;
				}
			}
			
			
			
			$allWords[$wordKey2]['topFive'] = $topFiveResult;
			//$allWords[$wordKey2]['topFive'] = $tempPrice;
			
			
			$req = new AlibabaScbpAdKeywordGetRequest;
			$query_dto = new KeywordQuery;
			$query_dto->is_exact="Y"; 
			$query_dto->keyword=$word2['keyword'];
			$req->setQueryDto(json_encode($query_dto));
			$resp = $c->execute($req, $sessionKey);    
			
			$basePriceResult = json_decode(json_encode($resp),true);
			$allWords[$wordKey2]['aliInfo'] = $basePriceResult;
			$basePriceResult = $basePriceResult['keyword_list']['keyword_result_dto'][0]['base_price'];
			$allWords[$wordKey2]['baseInfo']  = $basePriceResult;
			
			
			//$allWords[$wordKey2]['baseInfo'] = $tempbase;
		}
		
		
		//出价数组
		$addPriceList = array();
		$priceStr = array();
		foreach($allWords as $wordKey3=>$keyword){
			
			
		
			//前5价格
			$topFivePrice = $keyword['topFive'];
			//底价
			$basePrice    = $keyword['baseInfo'];
			//出价方案数组
			$stInfo       = $keyword['groupInfo']['strategy'];
			$price_stept  = $stInfo['price_stept'];
			$top_price    = $stInfo['top_price'];
			
			$topFiveArr = array();
			$topFiveArr[0]    = empty($topFivePrice[4])?0.0:$topFivePrice[4];
			$topFiveArr[1]    = empty($topFivePrice[3])?0.0:$topFivePrice[3];
			$topFiveArr[2]    = empty($topFivePrice[2])?0.0:$topFivePrice[2];
			$topFiveArr[3]    = empty($topFivePrice[1])?0.0:$topFivePrice[1];
			$topFiveArr[4]    = empty($topFivePrice[0])?0.0:$topFivePrice[0];
			
			
			
			
			
			$str      = '出价模式：';
			$isSelect = false;
			$price = 0.0;
			$isPrice = 1;
			//排名优先
			if($stInfo['isRankFirst']==1){
				
				$str.='排名优先';
				foreach($topFiveArr as $rowPrice){
					
					
					if($rowPrice<=$top_price){
						
						$price = $rowPrice;
						$isSelect = true;
					}
					
					
				}
			}else{
			//预算优先
			
				$str.='预算优先';
				foreach($topFiveArr as $rowPrice){
					
					if($rowPrice!=0){
						if($rowPrice<=$top_price){
						
							$price = $rowPrice;
							$isSelect = true;
							break;
						}
					}else{
						
						$price = $basePrice;
						$isSelect = true;
						break;
					}
					
					
				}
			}
			
			
			if(!$isSelect){
				
				if($stInfo['isBasePrice']==1){
					
					$price = $basePrice;
				}else{
					
					$price = $top_price;
				}
			}
			
			if($price>$top_price){
				
				$price  	= 0.0;
				$isPrice 	= 0;
			}
		
			if($price<$basePrice){
				
				$price  	= 0.0;
				$isPrice 	= 0;
			}
			
			$allWords[$wordKey3]['toPrice'] 	= $price;
			$allWords[$wordKey3]['desc']    	= $str;
			$allWords[$wordKey3]['isSelect']	= $isSelect;
			$allWords[$wordKey3]['isPrice'] 	= $isPrice;
			$allWords[$wordKey3]['basePrice'] 	= $basePrice;
		
			
			//$str =  '[{"keyword_id":"77624451993","value":"4.6"},{"keyword_id":"77625994739","value":"3.2"}]';
		}
		
		//吸错，1当前出价=原价钱 ，2低价>最高出价，3状态为关闭  ，4：星级小于3
		foreach($allWords as $errorKey=>$val){
			
			$flag = true;
			$str = '';
			
			$allWords[$errorKey]['errorMsg']  = array();
			$allWords[$errorKey]['errorCode'] = array();
			
			//低价>最高出价
			if($val['baseInfo']>$val['groupInfo']['strategy']['top_price']){
				
				$msg = '低价>最高出价';
				$allWords[$errorKey]['errorMsg'][]  = $msg;
				$allWords[$errorKey]['errorCode'][] = 2;
				$allWords[$errorKey]['isPrice']     = 0;   
			}
			
			//当前出价=原价钱
			if( $val['isPrice']==1 && ($val['toPrice']==$val['aliInfo']['keyword_list']['keyword_result_dto'][0]['price']) ){
				
				$msg = '当前出价=原价钱';
				$allWords[$errorKey]['errorMsg'][]  = $msg;
				$allWords[$errorKey]['errorCode'][] = 1;
				$allWords[$errorKey]['isPrice']     = 0;   
			}
			
			//星级小于3
			if($val['aliInfo']['keyword_list']['keyword_result_dto'][0]['qs_star']<3){
				
				$msg = '星级小于3';
				$allWords[$errorKey]['errorMsg'][] = $msg;
				$allWords[$errorKey]['errorCode'][] = 4;
				$allWords[$errorKey]['isPrice']     = 0;   
			}
			//状态为关闭
			if($val['aliInfo']['keyword_list']['keyword_result_dto'][0]['status']=='stopped'){
				
				$msg = '关键词状态为关闭';
				$allWords[$errorKey]['errorMsg'][] = $msg;
				$allWords[$errorKey]['errorCode'][] = 3;
				$allWords[$errorKey]['isPrice']     = 0;   
			}
			
		}
		
		$dataAllRec = array();
		$dataAllSav = array();
		
		foreach($allWords as $val){
				
			if($val['isPrice']==1){
				
				$data = array();
				$data['keyword_id'] = $val['keyword_id'];
				$data['value']      = $val['toPrice'];
				$priceStr[] = $data;
				
				$dataRec = array();
				$dataRec['title']        = '关键词:'.$val['keyword'].' 出价成功'; 
				$dataRec['price_change'] = $val['aliInfo']['keyword_list']['keyword_result_dto'][0]['price'].'->'.$val['toPrice'];
				$dataRec['keyword_id']   = $val['keyword_id'];
				$dataRec['keyword']      = $val['keyword'];
				$dataRec['error_status'] = 0;
				$dataRec['error_msg']    = '';
				$dataRec['member_id']    = $member_id;
				$dataRec['datetime']     = time();
				
				//$dataAllRec[] = $dataRec;
				M('precord')->add($dataRec);
			}else{
				
				$dataRec = array();
				$dataRec['title']        = '关键词:'.$val['keyword'].' 出价失败'; 
				$dataRec['price_change'] = $val['aliInfo']['keyword_list']['keyword_result_dto'][0]['price'].'->'.$val['aliInfo']['keyword_list']['keyword_result_dto'][0]['price'];
				$dataRec['keyword_id']   = $val['keyword_id'];
				$dataRec['keyword']      = $val['keyword'];
				$dataRec['member_id']    = $member_id;
				$dataRec['datetime']     = time();
				
				$errCoStr = '';
				$errMgStr = '';
				foreach($val['errorCode'] as $keyErr=>$errCode){
					
					if($keyErr==0){
						
						$errCoStr.=$errCode;
					}else{
						$errCoStr.=','.$errCode;
					}
					
					
				}
				
				foreach($val['errorMsg'] as $keyErr2=>$errMsg){
					
					if($keyErr2==0){
						
						$errMgStr.=$errMsg;
					}else{
						$errMgStr.=','.$errMsg;
					}
				}
				
				$dataRec['error_status'] = $errCoStr;
				$dataRec['error_msg']    = $errMgStr;
				
				//$dataAllRec[] = $dataRec;
				M('precord')->add($dataRec);
			}
			
			//更新关键词最近更新时间
			$data = array();
			$data['bidgroup_words_id']    = $val['bidgroup_words_id'];
			$data['last_price_time']      = time();
			
			//$dataAllSav = $data[];
			M('bidgroup_words')->save($data);
		}
		
		//M('precord')->addAll($dataAllRec);
		//M('bidgroup_words')->saveAll($dataAllSav);
		
		$priceStr = json_encode($priceStr);
		
		$c = new TopClient;
		$c->appkey = APP_KEY;
		$c->secretKey = APP_SECRET;
		$req = new AlibabaScbpAdKeywordPriceBatchupdateRequest;
		
		$keyword_update_dto_list = new KeywordUpdateDto;
		
		$req->setKeywordUpdateDtoList($priceStr);
		
		$resp = $c->execute($req, $sessionKey);
		
		
		
		
		
		$member_id 	    = $this->member_id;
		$precord_id =  empty($_REQUEST['precord_id'])?'':$_REQUEST['precord_id'];
		
		import('ORG.Util.Page');
		
		$where = array();
		$where['member_id'] = $member_id;
		if(!empty($precord_id)){
			$where['precord_id'] = array('gt',$precord_id);
		}
		
		//$where['_string']='FIND_IN_SET("1", error_status)';
		
		$count      = M('precord')->where($where)->count();
		$Page       = new Page($count,5);
		$show       = $Page->show();
		$lists = M('precord')->where($where)->order('precord_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
		
		$lists = empty($lists)?array():$lists;
		
		$lists = count($groupList)>0?$lists:array();
		
		//删除该用户24小时前的出价记录
		/*
		$where = '';
		$where = 'member_id ='.$member_id.' AND ('.time().'  - datetime) > 86400';
		
		if($nowHour=='7'){
			M('precord')->where($where)->delete();
		}
		*/
		
		
		$return  = array();
		$return['status']      = 1;
		$return['data']   	   =  $lists;
		$return['member_id']   =  $member_id;
		$this->returnData($return);
	}
	
	
	
	public function copyAllGroupWords(){
		
		set_time_limit(0);
		
		$sessionKey 	=  $this->sessionKey;
		$username 		= empty($_REQUEST['username'])?'':$_REQUEST['username'];
		$bidgroup_id 	= empty($_REQUEST['bidgroup_id'])?0:$_REQUEST['bidgroup_id'];
		$action 		= empty($_REQUEST['action'])?'':$_REQUEST['action'];
		
		$member_id 	    = $this->member_id;
		
		$c = new TopClient; 
		$c->appkey 		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		
		$req  = new AlibabaScbpTagListRequest; 
		$resp = $c->execute($req, $sessionKey);
		
		$groupAllList = json_decode(json_encode($resp),true);
		
		$groupAllList = $groupAllList['tag_list']['tag_group'];
		
		
		
		if($action=='single'){
			
			$groupInfo = M('bidgroup')->where('bidgroup_id='.$bidgroup_id)->find();
			
			foreach($groupAllList as $key=>$val){
				
				if($val['id']==$groupInfo['aligroup_id']){
					
				}else{
					
					unset($groupAllList[$key]);
				}
			}
		}else{
			
			$groupOldList = M('bidgroup')->where('member_id='.$member_id)->select();
			
			foreach($groupOldList as $old){
				
				$flag = false;
				
				foreach($groupAllList as $new){
					
					if($old['aligroup_id']==$new['id']){
						
						$flag = true;
					}
				}
				if(!$flag){
					
					M('bidgroup')->where('bidgroup_id='.$old['bidgroup_id'])->delete();
					M('bidgroup_words')->where('bidgroup_id='.$old['bidgroup_id'])->delete();
				}
			}
		}
		
		
		
		foreach($groupAllList as $groupKey=>$group){
			
			
			if($group['id']!='-1'){
				
				$dataGroup = array();
				$dataGroup['title']      = $group['name'];
				$dataGroup['member_id']  = $member_id;
				$dataGroup['bid_status'] = 0;
				$dataGroup['aligroup_id']= $group['id'];
				
				$where = array();
				$where['member_id']     = $member_id;
				$where['aligroup_id'] 	= $group['id'];
				
				$bidgroupInfo = M('bidgroup')->where($where)->find();
				
				if(empty($bidgroupInfo)){
					
					$bidgroup_id = M('bidgroup')->add($dataGroup);
					
					//添加出价基础方案
					$dataStra = array();
					$dataStra['title'] 		= '默认规则';
					$dataStra['group_id'] 	= $bidgroup_id;
					$dataStra['member_id'] 	= $member_id;
					$dataStra['description']= 	'默认规则作为基础规则，不能删除。在没有设置其他时段的规则时候按照默认规则出价。';
					$dataStra['is_default'] = 	1;
					$dataStra['price_speed']= 	5;
					$dataStra['top_price']  = 	20;
					$dataStra['startTime']	=	'00/**/00/**/00';
					$dataStra['endTime']	=	'23/**/59/**/59';
					$dataStra['type']		=	1;
					$dataStra['status']		=	1;
					$dataStra['price_stept']=	0.1;
					$dataStra['isRankFirst']=	0;
					$dataStra['isBasePrice']=	0;
					
					M('strategy')->add($dataStra);
				}else{
					
					$dataSave = array();
					$dataSave['bidgroup_id'] = $bidgroupInfo['bidgroup_id'];
					$dataSave['title'] 		 = $group['name'];
					
					M('bidgroup')->save($dataSave);
					
					$bidgroup_id = $bidgroupInfo['bidgroup_id'];
				}
				
				$del = M('bidgroup_words')->where('bidgroup_id='.$bidgroup_id.' AND member_id='.$member_id)->delete();
				
				
				
				
				//计算关键词总页数
				$totalPage = 1;
				
				$totalCount = $group['count'];
				
				if($totalCount<=50){
					
					$totalPage = 1;
				}else{
					
					$totalPage = intval($totalCount/50);
					$yu        = $totalCount%50;
					if($yu!=0){
						$totalPage = $totalPage+1;
					}
				}
				
				
				$c = new TopClient;
				$c->appkey 		= APP_KEY;
				$c->secretKey 	= APP_SECRET;
				$req 			= new AlibabaScbpAdKeywordGetRequest;
				$query_dto 		= new KeywordQuery;
				$query_dto->tag_name		= $group['name'];
				$query_dto->per_page_size	= "50";
				// $query_dto->to_page	=	1;
				// $req->setQueryDto(json_encode($query_dto));
				// $resp = $c->execute($req, $sessionKey);
				
				$groupAllWords = array();
				for($i=1;$i<=$totalPage;$i++){
					
					$query_dto->to_page	=	$i;
					$req->setQueryDto(json_encode($query_dto));
					$resp = $c->execute($req, $sessionKey);
					
					$groupPageWords =array();
					$groupPageWords = json_decode(json_encode($resp),true);
					$totalCountNew  = $groupPageWords['total_num'];
					$groupPageWords = $groupPageWords['keyword_list']['keyword_result_dto'];
					
					foreach($groupPageWords as $word){
						
						$dataWord = array();
						$dataWord['bidgroup_id'] = $bidgroup_id;
						$dataWord['member_id'] 	 = $member_id;
						$dataWord['keyword_id']  = $word['id'];
						
						$dataWord['base_price']  	= $word['base_price'];
						$dataWord['buy_count'] 	 	= $word['buy_count'];
						$dataWord['click_cnt'] 	 	= $word['click_cnt'];
						$dataWord['click_cost_avg']	= $word['click_cost_avg'];
						$dataWord['cost'] 	 		= $word['cost'];
						$dataWord['ctr'] 	 		= $word['ctr'];
						
						$dataWord['impression_cnt']  = $word['impression_cnt'];
						$dataWord['match_count'] 	 = $word['match_count'];
						$dataWord['online_time'] 	 = $word['online_time'];
						$dataWord['price'] 	 		 = $word['price'];
						$dataWord['qs_star'] 	 	 = $word['qs_star'];
						$dataWord['search_count'] 	 = $word['search_count'];
						$dataWord['status'] 	 	 = $word['status'];
						$dataWord['keyword'] 	 	 = $word['word'];
						$dataWord['tag_list'] 	 	 = implode(',',$word['tag_list']['string']);
						
						$groupAllWords[] = $dataWord;
					}
				}
				
				
				M('bidgroup_words')->addAll($groupAllWords);
				
				
			}
		}
		
		
		$return  = array();
		$return['data']   =  1;
		$return['status'] =  1;
		$this->returnData($return);
	}
	
	
	// public function reflashGroupWords(){
		
		// $sessionKey 	= empty($_REQUEST['sessionKey'])?'':$_REQUEST['sessionKey'];
		// $username 		= empty($_REQUEST['username'])?'':$_REQUEST['username'];
		// $bidgroup_id	= empty($_REQUEST['bidgroup_id'])?0:$_REQUEST['bidgroup_id'];
		
		// $member_id 	    = $this->getMemId($username);
		
		// $where = array();
		// $where['bidgroup_id'] = $bidgroup_id;
		// $where['member_id']   = $member_id;
	
		// $bidInfo    = M('bidgroup')->where($where)->find();
		
		
		// $c = new TopClient;
		// $c->appkey 		= APP_KEY;
		// $c->secretKey 	= APP_SECRET;
		// $req = new AlibabaScbpAdKeywordGetRequest;
		// $query_dto = new KeywordQuery;
		
		// if(!empty($tag_name)){ 
			// $query_dto->tag_name		=	$tag_name; 
		// }
		
		// if(!empty($to_page)){ 
			// $query_dto->to_page		=	$to_page; 
		// }
		
		// $query_dto->per_page_size	=	$per_page_size;
		// $req->setQueryDto(json_encode($query_dto));
		// $resp = $c->execute($req, $sessionKey);
		
	// }
	
	public function bidGroupBatchAddWords(){
		
		
		$keyword_ids 	= empty($_REQUEST['keyword_ids'])? '': $_REQUEST['keyword_ids'];
		$group_ids 	    = empty($_REQUEST['group_ids'])? '': $_REQUEST['group_ids'];
		
		$sessionKey 	=  $this->sessionKey;
		
		$keywordArr = array();
		$keywordArr = explode(DOT,trim($keyword_ids,DOT));
		
		$groupArr   = explode(DOT,trim($group_ids,DOT));
		
		$keywordStr = '';
		$groupStr   = '';
		
		foreach($keywordArr as $key=>$val){
			
			if(!empty($val)){
				
				if($key==0){
					
					$keywordStr.=$val;
				}else{
					$keywordStr.=','.$val;
				}
			}
		}
		
		foreach($groupArr as $key=>$val){
			
			if(!empty($val)){
				
				if($key==0){
					
					$groupStr.=$val;
				}else{
					$groupStr.=','.$val;
				}
			}
		}
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		$req = new AlibabaScbpAdKeywordTagUpdateRequest;
		$req->setKeywordIdList($keywordStr);
		$req->setTagIdList($groupStr);
		$resp = $c->execute($req, $sessionKey);
		
		$return  = array();
		$return['data']    =  1;
		$return['status']   =  1;
		
		$this->returnData($return);
	}
	
	public function getMemInfo(){
		
		$where = array();
		$where['username_md5'] = $_REQUEST['u'];
		
		$memberInfo  =  M('member')->where($where)->find();
		
		$return  = array();
		$return['status']   =  1;
		$return['data']     =  array();
		
		if(!empty($memberInfo)){
			
			unset($memberInfo['access_token']);
			$return['data'] = $memberInfo;
			
			$stept = intval(($memberInfo['endtime'] - $memberInfo['addtime'])/86400);
			$return['days'] = $stept;
			
			
		}else{
			$return['status']   =  0;
		}
		
		$this->returnData($return);
	}
	
	
	public function getDayCost($sessionKey){
		
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		$req = new AlibabaScbpAccountDaycostGetRequest;
		$resp = $c->execute($req, $sessionKey);
		$resp = json_decode(json_encode($resp),true);
		
		return $day_cost = $resp['day_cost'];
	}
	
	public function getBudget($sessionKey){
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		$req = new AlibabaScbpAccountBudgetGetRequest;
		$resp = $c->execute($req, $sessionKey);
		$resp = json_decode(json_encode($resp),true);
		
		return $budget = $resp['budget'];
		
	}
	
	
	public function test(){
		
		$this->display();
	}
	
	
	
	//返回处理方法
	public function returnData($data){
		
		header("Access-Control-Allow-Origin: *");
		header("Content-type: text/html; charset=utf-8");
		echo json_encode($data);
		exit;
	}
	
	//根据阿里巴巴账号获取用户ID
	public function getMemId($username){
		
		$cond = array();
		$cond['username'] = $username;
		
		$userInfo = M('member')->where($cond)->find();
		
		if($userInfo){
			
			return $userInfo['member_id'];
		}else{
			
			return '0';
		}
	}
	
	public function getMemToken($username){
		
		$cond = array();
		$cond['username_md5'] = $username;
		
		$userInfo = M('member')->where($cond)->find();
		
		if($userInfo){
			
			return $userInfo['access_token'];
		}else{
			
			return '0';
		}
	}
	

	
	
	
	
	
	
	
}
?>